<template>
  <view class="pre-fee-detail-page">
    <!-- 顶部导航/标题区 -->
    <view class="header-section">
      <view class="header-left">
        <view class="title-section">
          <text class="main-title">预付费明细</text>
          <text class="sub-title">自动退款</text>
        </view>
      </view>
      <view class="header-right">
        <text class="rule-text" @click="showRules">规则</text>
        <view class="rule-icon">
          <uni-icons type="calendar" size="24" color="#ff6b35"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 规则说明区 -->
    <view class="rules-section">
      <view class="rule-item">
        <text class="rule-text">1、订单<text style="color: #fc8112;">支付完成</text>如有剩余金额，会<text style="color: #fc8112;">原支付路径</text>退款</text>
      </view>
      <view class="rule-item">
        <text class="rule-text">2、如充电订单推送延迟，预付费会暂存于充电订单中</text>
      </view>
      <view class="rule-item">
        <text class="rule-text">3、如超7个工作日未退款成功可联系客服处理</text>
      </view>
    </view>

    <!-- 交易列表区 -->
    <view class="transaction-section">
      <!-- Tab切换 -->
      <view class="tab-header">
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'recharge' }"
          @click="switchTab('recharge')"
        >
          充值
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'refund' }"
          @click="switchTab('refund')"
        >
          退款
        </view>
      </view>

      <!-- 交易列表 -->
      <view class="transaction-list">
        <view 
          class="transaction-item" 
          v-for="(item, index) in currentTransactions" 
          :key="index"
          @click="goToDetail(item)"
        >
          <view class="transaction-left">
            <view class="transaction-icon" :class="item.type">
              <text class="icon-text">{{ item.iconText }}</text>
            </view>
            <view class="transaction-info">
              <text class="transaction-name">{{ item.name }}</text>
              <text class="payment-method">{{ item.paymentMethod }}</text>
              <text class="transaction-time">{{ item.time }}</text>
            </view>
          </view>
          <view class="transaction-right">
            <text class="transaction-amount" :class="item.type">
              {{ item.amount }}
            </text>
            <text v-if="item.type === 'refund'" class="refund-status">已退款</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 规则弹窗 -->
    <uni-popup ref="rulesPopup" type="center" :maskClick="true" :animation="true" :safeArea="true">
      <view class="rules-popup-content">
        <view class="rules-popup-header">
          <text class="rules-popup-title">预付费规则</text>
        </view>
        <view class="rules-popup-body">
          <view class="rule-item-popup">
            <text class="rule-number">1、</text>
            <text class="rule-text-popup">充电时预付费用；充电结束后，系统将自动根据实际消费金额进行结算，多余部分退还。</text>
          </view>
          <view class="rule-item-popup">
            <text class="rule-number">2、</text>
            <text class="rule-text-popup">如充电订单推送延迟，预付费会暂存于订单中，不会有资金安全问题，请您耐心等待，订单信息将尽快推送至您的账户。</text>
          </view>
          <view class="rule-item-popup">
            <text class="rule-number">3、</text>
            <text class="rule-text-popup">订单支付成功后，若有余额，余额将自动沿原支付路径返还；请留意您的支付平台，若超时未退回，请联系客服处理。</text>
          </view>
          <view class="rule-item-popup">
            <text class="rule-number">4、</text>
            <text class="rule-text-popup">您可以在【我的】-【预付费明细】查看预付费明细。</text>
          </view>
        </view>
        <view class="rules-popup-footer">
          <view class="rules-confirm-btn" @click="hideRules">我知道了</view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue'
import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
import { getMyOrderPage } from '@/api/charging/index.js'

export default {
  components: {
    uniPopup,
    uniIcons
  },
  data() {
    return {
      activeTab: 'recharge',
      rechargeTransactions: [], // 改为空数组，由接口数据填充
      refundTransactions: [], // 改为空数组，由接口数据填充
      // 从订单详情页传递的参数
      orderNum: '',
      orderNumber: '',
      orderRealPrice: 0,
      advanceTotal: 0,
      chargeBalanceAdvance: 0,
      cashAdvance: 0,
      payChannel: '',
      paySuccessTime: '',
      stationName: '',
      carNumber: '',
      // 退款相关字段
      chargeBalanceRefund: 0,
      cashPayRefund: 0
    }
  },
  computed: {
    currentTransactions() {
      return this.activeTab === 'recharge' ? this.rechargeTransactions : this.refundTransactions;
    }
  },
  onLoad(options) {
    console.log('预付费用详情页面接收到的参数:', options);
    
    // 从URL参数获取数据
    this.orderNum = options.orderNum || '';
    this.orderNumber = options.orderNumber || '';
    this.orderRealPrice = parseFloat(options.orderRealPrice) || 0;
    this.advanceTotal = parseFloat(options.advanceTotal) || 0;
    this.chargeBalanceAdvance = parseFloat(options.chargeBalanceAdvance) || 0;
    this.cashAdvance = parseFloat(options.cashAdvance) || 0;
    this.payChannel = options.payChannel || '';
    this.paySuccessTime = options.paySuccessTime || '';
    this.stationName = options.stationName || '';
    this.carNumber = options.carNumber || '';
    
    // 如果有传递的退款数据，也获取
    if (options.chargeBalanceRefund) {
      this.chargeBalanceRefund = parseFloat(options.chargeBalanceRefund) || 0;
    }
    if (options.cashPayRefund) {
      this.cashPayRefund = parseFloat(options.cashPayRefund) || 0;
    }
    
    console.log('处理后的数据:', {
      orderNum: this.orderNum,
      orderNumber: this.orderNumber,
      orderRealPrice: this.orderRealPrice,
      advanceTotal: this.advanceTotal,
      chargeBalanceAdvance: this.chargeBalanceAdvance,
      cashAdvance: this.cashAdvance,
      chargeBalanceRefund: this.chargeBalanceRefund,
      cashPayRefund: this.cashPayRefund
    });
    
    // 调用接口获取订单数据
    this.getOrderData();
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    // 获取订单数据
    getOrderData() {
      const params = {
        page: 1,
        rows: 10000,
        type: 1 // 固定为1，预付款记录(全部)
      };
      
      getMyOrderPage(params)
        .then(response => {
          console.log('获取订单数据成功:', response);
          if (response.success && response.data && response.data.records) {
            this.processOrderData(response.data.records);
          }
        })
        .catch(error => {
          console.error('获取订单数据失败:', error);
        });
    },
    
    // 处理订单数据
    processOrderData(records) {
      // 清空现有数据
      this.rechargeTransactions = [];
      this.refundTransactions = [];
      
      records.forEach(record => {
        // 处理充值记录
        const rechargeItem = {
          id: record.id,
          name: record.title || '充值',
          paymentMethod: this.getPaymentMethodText(record),
          time: this.formatTime(record.createTime),
          amount: `+${record.advanceTotal}`,
          type: 'recharge',
          iconText: '充',
          // 保存原始数据用于详情页
          originalData: record
        };
        this.rechargeTransactions.push(rechargeItem);
        
        // 如果有退款，处理退款记录
        // 根据说明，退款使用chargeBalanceRefund字段
        if (record.payState === 4 && (record.chargeBalanceRefund > 0 || record.cashPayRefund > 0)) {
          const refundAmount = (record.cashPayRefund || 0) + (record.chargeBalanceRefund || 0);
          if (refundAmount > 0) {
            const refundItem = {
              id: record.id,
              name: '退款',
              paymentMethod: this.getPaymentMethodText(record),
              time: this.formatTime(record.refundSuccessTime || record.refundTime),
              amount: `-${refundAmount}`,
              type: 'refund',
              iconText: '退',
              // 保存原始数据用于详情页
              originalData: record
            };
            this.refundTransactions.push(refundItem);
          }
        }
      });
      
      console.log('处理后的交易数据:', {
        recharge: this.rechargeTransactions,
        refund: this.refundTransactions
      });
    },
    
    // 获取支付方式文本
    getPaymentMethodText(record) {
      const chargeBalanceAdvance = record.chargeBalanceAdvance || 0;
      const cashAdvance = record.cashAdvance || 0;
      
      if (chargeBalanceAdvance > 0 && cashAdvance > 0) {
        return '组合支付';
      } else if (chargeBalanceAdvance > 0) {
        return '钱包余额支付';
      } else {
        return '微信支付';
      }
    },
    
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return '';
      // 处理时间格式，去掉毫秒部分
      return timeStr.split('.')[0].replace('T', ' ');
    },
    switchTab(tab) {
      this.activeTab = tab;
    },
    showRules() {
      if(this.$refs.rulesPopup) {
        this.$refs.rulesPopup.open('center');
      }
    },
    hideRules() {
      if(this.$refs.rulesPopup) {
        this.$refs.rulesPopup.close();
      }
    },
    goToDetail(item) {
      // 将订单数据编码后传递到详情页
      const orderData = encodeURIComponent(JSON.stringify(item.originalData));
      uni.navigateTo({
        url: `/pages/preFeeDetail/detail?type=${item.type}&orderData=${orderData}`
      });
    }
  }
}
</script>

<style scoped>
.pre-fee-detail-page {
  background: #f5f5f5;
  min-height: 100vh;
  padding: 0;
}

/* 顶部导航/标题区 */
.header-section {
  background: #fff;
  padding: 40rpx 30rpx 30rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  border-bottom: 1rpx solid #f0f0f0;
}

.header-left {
  padding-left: 20rpx;
  display: flex;
  align-items: flex-start;
}

.back-icon {
  margin-right: 20rpx;
  padding: 10rpx;
}

.title-section {
  display: flex;
  flex-direction: column;
}

.main-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #ff6b35;
  margin-bottom: 8rpx;
}

.sub-title {
  font-size: 24rpx;
  color: #999;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.rule-text {
  font-size: 24rpx;
  color: #ff6b35;
  font-weight: 700;
}

.rule-icon {
  padding: 5rpx;
}

/* 规则说明区 */
.rules-section {
  margin: 20rpx 30rpx;
  padding: 30rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.rule-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.rule-item:last-child {
  margin-bottom: 0;
}

.rule-number {
  width: 40rpx;
  height: 40rpx;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  font-weight: bold;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.rule-text {
  font-size: 22rpx;
  color: #c13d31;
  line-height: 1.5;
  flex: 1;
}

/* 交易列表区 */
.transaction-section {
  margin: 20rpx 30rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/* Tab切换 */
.tab-header {
  display: flex;
  border-bottom: 1rpx solid #f0f0f0;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 30rpx 0;
  font-size: 28rpx;
  color: #999;
  position: relative;
  transition: all 0.3s ease;
}

.tab-item.active {
  color: #333;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background: #ff6b35;
  border-radius: 2rpx;
}

/* 交易列表 */
.transaction-list {
  padding: 0 30rpx;
}

.transaction-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.transaction-item:last-child {
  border-bottom: none;
}

.transaction-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.transaction-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.transaction-icon.recharge {
  background: #ff6b35;
}

.transaction-icon.refund {
  background: #52c41a;
}

.icon-text {
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
}

.transaction-info {
  display: flex;
  flex-direction: column;
}

.transaction-name {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.payment-method {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 6rpx;
}

.transaction-time {
  font-size: 24rpx;
  color: #999;
}

.transaction-right {
  text-align: right;
}

.transaction-amount {
  font-size: 32rpx;
  font-weight: bold;
}

.transaction-amount.recharge {
  color: #ff6b35;
}

.transaction-amount.refund {
  color: #52c41a;
}

.refund-status {
  font-size: 22rpx;
  color: #52c41a;
  display: block;
  margin-top: 6rpx;
}

/* 规则弹窗样式 */
.rules-popup-content {
  width: 90%;
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.15);
  margin: 0 auto;
}

.rules-popup-header {
  width: 100%;
  text-align: center;
  padding: 40rpx 30rpx 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.rules-popup-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.rules-popup-body {
  width: 90%;
  padding: 30rpx;
}

.rule-item-popup {
  display: flex;
  align-items: flex-start;
  margin-bottom: 25rpx;
  flex-wrap: wrap;
}

.rule-item-popup:last-child {
  margin-bottom: 0;
}

.rule-number {
  font-size: 28rpx;
  font-weight: bold;
  color: #ff6b35;
  margin-right: 15rpx;
  flex-shrink: 0;
  line-height: 1.6;
}

.rule-text-popup {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
  flex: 1;
}

.rules-popup-footer {
  width: 90%;
  padding: 20rpx 30rpx 40rpx 30rpx;
  text-align: center;
}

.rules-confirm-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background: #ff6b35;
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 44rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 107, 53, 0.3);
}
</style>
